$(function () {
    //ucCenterScroll();
    $("body").on('click', '#startDate', function () { //时间
        laydate({event: 'focus'});
    }).on('click','.updateUserAddress',function () {
        var id= $(this).data('id');
        toNewUpdateUserAddress(id);
    });
    //增改收货地址
    addressFn();
    if(pageTag==null || $.trim(pageTag) ==''){
        //基本信息
        baseUserInfo();
    }else if(pageTag=='userAcademicInfo'){
        var em = $('[data-id="userAcademicInfo"]');
        $(em).addClass('active').siblings().removeClass('active');
        getMyAcademic();
    }else if (pageTag=='avatarSettings'){
        var em = $('[data-id="avatarSettings"]');
        $(em).addClass('active').siblings().removeClass('active');
        getUserImg();
    }
    //上部导航
    topNavigation();
    //修改手机跳转页面
    updateMobileAndEmail();
    //修改用户信息
    submitPersonalDataForm();
    //修改用户地址状态
    updateNewUserAddressStatus();
    //删除用户地址
    deleteNewUserAddress();
    //修改用户密码
    openNewUpdatePassWord();

})
/**
 * 上部导航栏
 */
function topNavigation() {
    $('section.c-info-tab h4').click(function () {
        $(this).addClass('active').siblings().removeClass('active');
        var id = $(this).data('id');
        if (id == 'basicStatistics') {
            baseUserInfo();
        } else if (id == 'userAcademicInfo') {
            getMyAcademic();
        } else if (id == 'avatarSettings') {
            getUserImg();
        }else if (id == 'accountSecurity') {
            securityOfAccounts();
        }else if (id == 'shippingAddress') {
            getMyAddress();
        }
    });
}
//增改收货地址
var addressFn = function () {
    $('body').on('click', '#addAddRessBtn', function () {
        var params = $("#addUserAddress").serializeJSON();
        params = JSON.stringify(params);
        $.ajax({
            url: baseloaction + "/web/uc/ajax/saveUserAddress",
            data:params,
            dataType: "json",
            type: "post",
            contentType:'application/json;charset=utf-8',
            success: function (result) {
                if (result.success == true) {
                    icModale(0,"",result.message,null,null,null);
                    getMyAddress();
                } else {
                    if(result.entity!=null){
                        icModale(0, "", result.message, null, null, null);
                        /*  $("#"+result.entity).html('<i class="fa fa-warning"></i>'+result.message);*/
                    }else{
                        icModale(0, "", result.message, null, null, null);
                    }
                }
            }
        });
    });
}
/**
 * 用户头像
 */
function getUserImg() {
    getPageAjaxData({
        url: baseloaction + "/web/uc/ajax/setFaceImage",
        contextId:'ajaxContext',
        callback: function () {
            initAvatar();
        }
    });
}
/**
 * 基本信息
 */
function baseUserInfo() {
    getPageAjaxData({
        url: baseloaction + "/web/uc/ajax/baseUserInfo",
        contextId:'ajaxContext',
        callback: function () {
        }
    });
}
/**
 * 账户安全
 */
function securityOfAccounts() {
    getPageAjaxData({
        url: baseloaction + "/web/uc/ajax/securityOfAccounts",
        contextId:'ajaxContext',
        callback: function () {
        }
    });
}
/**
 * 收货地址
 */
function getMyAddress() {
    getPageAjaxData({
        url: baseloaction + "/web/uc/ajax/myAddress",
        contextId:'ajaxContext',
        callback: function () {
            queryNewAddress(0, 0, 0);
        }
    });
}

/**
 * 修改个人资料
 */
function submitPersonalDataForm() {
    $('body').on('click', '#submitPersonalDataForm', function () {
        var nickname =$('input[name="nickname"]').val();
        var  realName=$('input[name="realName"]').val();
        var boolean;
        boolean=judgmentString(nickname,"昵称");
        if(boolean==false){return;}
        //boolean=judgmentString(realName,"真实姓名");
        //if(boolean==false){return;}
        var params = $("#personalDataForm").serializeJSON();
        params = JSON.stringify(params);
        $.ajax({
            url: baseloaction + "/web/uc/ajax/saveUserPersonalData",
            data: params,
            type: 'post',
            dataType: 'json',
            contentType:'application/json;charset=utf-8',
            success: function (result) {
                var userObj = result.entity;
                userObj = JSON.parse(userObj);
                var nickname = userObj.nickname;
                $("#nickname").html(nickname);
                $("input[name=realName]").val(userObj.realName);
                $("textarea[name=userInfo]").val(userObj.userInfo);
                icModale(0, "", result.message, null);
            },
            error:function () {
                icModale(0, "", "系统繁忙，请稍后再试", null);
            }
        });
    })
}
function judgmentString(str,name) {
    if(str==null||str==''){
        icModale(0,"","请输入"+name);
        return false;
    }else{
        if (isEmojiCharacter(str.trim())) {
            icModale(0,"",name+"不能含有表情");
            return false;
        }
    }
}
/**
 * 是否有表情
 * @param substring
 * @returns {boolean}
 */
function isEmojiCharacter(substring) {
    for (var i = 0; i < substring.length; i++) {
        var hs = substring.charCodeAt(i);
        if (0xd800 <= hs && hs <= 0xdbff) {
            if (substring.length > 1) {
                var ls = substring.charCodeAt(i + 1);
                var uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                if (0x1d000 <= uc && uc <= 0x1f77f) {
                    return true;
                }
            }
        } else if (substring.length > 1) {
            var ls = substring.charCodeAt(i + 1);
            if (ls == 0x20e3) {
                return true;
            }
        } else {
            if (0x2100 <= hs && hs <= 0x27ff) {
                return true;
            } else if (0x2B05 <= hs && hs <= 0x2b07) {
                return true;
            } else if (0x2934 <= hs && hs <= 0x2935) {
                return true;
            } else if (0x3297 <= hs && hs <= 0x3299) {
                return true;
            } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030
                || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b
                || hs == 0x2b50) {
                return true;
            }
        }
    }
}
/**
 * 查询省/市/县
 * @param parentId 父行政区划id
 * @param areaType 0.省级 1.市级 2.县级
 * @param select 默认值
 * @param callback 下级行政区划回调
 */
function queryNewAddress(parentId, areaType, select, callback) {
    $.ajax({
        url: baseloaction + "/web/uc/ajax/queryAreaListByParentId",
        data: {"parentId": parentId, 'areaType': areaType},
        dataType: "json",
        type: "post",
        success: function (result) {
            if (result.success == true) {
                var userAddress = result.entity;
                //switch fall-through
                switch (areaType) {
                    case 0 :
                        $('#areaType_' + 0).html('<option selected value="0">--请选择省--</option>');
                    case 1 :
                        $('#areaType_' + 1).html('<option selected value="0">--请选择市--</option>');
                    case 2 :
                        $('#areaType_' + 2).html('<option selected value="0">--请选择县--</option>');
                        break;
                }
                if (userAddress && userAddress.length > 0) {
                    for (var i = 0; i < userAddress.length; i++) {
                        $('#areaType_' + areaType).append('<option value="' + userAddress[i].id + '">' + userAddress[i].areaName + '</option>');
                    }
                }
                if (select) $('#areaType_' + areaType).val(select);
                if ($.isFunction(callback)) callback(select);
            }
        }
    });
}
//修改收货地址
function updateUserAddress() {
    $('body').on('click', '#updateUserAddress', function () {
        var id = $(this).data('id');
        var _ele = $('#addAddRessEle').val();
        layer.open({
            type: 1,
            title: '修改收货地址<span class="ml10 fs12 c-999"><small class="fs12 c-danger">*</small>为必填项</span>',
            area: ['960px', '580px'],
            shadeClose: true,
            skin: 'lay_ppComment__wrap',
            content: _ele,
            success: function () {
                toNewUpdateUserAddress(id);
            },
            btn: [' 确定 ', ' 取消 '],
            yes: function (index, layero) {
                var params = $("#addUserAddress").serializeJSON();
                params = JSON.stringify(params);
                $.ajax({
                    url: baseloaction + "/web/uc/ajax/saveUserAddress",
                    data: params,
                    dataType: "json",
                    type: "post",
                    contentType:'application/json;charset=utf-8',
                    success: function (result) {
                        if (result.success == true) {
                            icModale(0, "", result.message, null);
                            window.location.reload();
                            layer.close(index);
                        } else {
                            icModale(0, "", result.message, null);
                        }
                    }
                });
            },
            btn2: function (index, layero) {
                layer.close(index)
            }
        })
    })
}
//修改用户地址
function toNewUpdateUserAddress(id) {
    $.ajax({
        url: baseloaction + "/web/uc/ajax/queryUserAddressById",
        data: {"addressId": id},
        dataType: "json",
        type: "post",
        success: function (result) {
            if (result.success == true) {
                $('input[name="receiver"]').val(result.entity.receiver);
                $('input[name="mobile"]').val(result.entity.mobile);
                $('input[name="address"]').val(result.entity.address);
                $('input[name="postCode"]').val(result.entity.postCode);
                $('input[name="id"]').val(result.entity.id);
                if(result.entity.status==1){
                    $('input[name="status"]').attr("checked",true);
                }else {
                    $('input[name="status"]').attr("checked",false);
                }
                queryNewAddress(0, 0, result.entity.provinceId, function (parentId) {
                    queryNewAddress(parentId, 1, result.entity.cityId, function (parentId) {
                        queryNewAddress(parentId, 2, result.entity.townId);
                    })
                });
            } else {
                icModale(0, "", result.message, null);
            }
        }
    });
}
//删除用户地址
function deleteNewUserAddress() {
    $('body').on('click', '#deleteUserAddress', function () {
        var obj =$(this);
        var id = $(this).data('id');
        $.ajax({
            url: baseloaction + "/web/uc/ajax/deleteUserAddressById",
            data: {"addressId": id},
            dataType: "json",
            type: "post",
            success: function (result) {
                if (result.success == true) {
                    console.log(obj.parent());
                    console.log(obj.parent().parent());
                    obj.parent().parent().remove();
                    icModale(0, "", result.message, null);
                } else {
                    icModale(0, "", result.message, null);
                }
            }
        });
    })
}
/**
 * 修改用户是否是常用地址
 */
function updateNewUserAddressStatus() {
    $('body').on('click','#updateUserAddressStatus', function () {
        var id = $(this).data('id');
        var status = $(this).data('status');
        $.ajax({
            url: baseloaction + "/web/uc/ajax/updateUserAddressStatus",
            data: {"addressId": id, "status": status},
            dataType: "json",
            type: "post",
            success: function (result) {
                if (result.success == true) {
                    icModale(0, "", result.message, null);
                    getMyAddress();
                } else {
                    icModale(0, "", result.message, null);
                }
            }
        });
    })
}
/**
 * 点击编辑邮箱和手机 跳转页面
 */
function updateMobileAndEmail() {
    $('body').on('click', '.updateMobileAndEmail', function () {
        $('#accountSecurity').addClass('active').siblings().removeClass('active');
        $.ajax({
            url:baseloaction+"/web/uc/ajax/securityOfAccounts",
            type:"post",
            dataType:"html",
            success:function(result){
                $("#ajaxContext").html(result);
            }
        });
    });
}
/**
 * 修改密码弹出框 并修改
 */
function openNewUpdatePassWord() {
    var publicKey = '';
    var sign = '';
    $('body').on('click', '#newUpdatePassWordBtn', function () {
        $.ajax({
            url: baseloaction+ '/web/uc/getKeyMap',
            type:'json',
            dataType:'json',
            async:false,
            success:function (res) {
                if(res.success==true){
                    var obj = res.entity;
                    publicKey = obj.publicKey;
                    sign = obj.sign;
                }
            }
        });
        var _ele = $('#newUpdatePassWord').html();
        var str ='修改密码';
        icModale(2, '<strong>'+str+'</strong>', _ele, '确认', '520px', function(index, ele) {
            var nowPwd = ele.find('input[name="nowPwd"]').val();
            var newPwd = ele.find('input[name="newPwd"]').val();
            var confirmPwd = ele.find('input[name="confirmPwd"]').val();
            if (nowPwd == null || nowPwd == '') {
                ele.find('input[name="nowPwd"]').addClass('has-error');
            } else {
                ele.find('input[name="nowPwd"]').addClass('has-success');
            }
            if (newPwd == null || newPwd == '') {
                ele.find('input[name="newPwd"]').addClass('has-error');
            } else {
                ele.find('input[name="newPwd"]').addClass('has-success');
            }
            if (confirmPwd == null || confirmPwd == '') {
                ele.find('input[name="confirmPwd"]').addClass('has-error');
            } else {
                ele.find('input[name="confirmPwd"]').addClass('has-success');
            }
            if(nowPwd !=null && $.trim(nowPwd) !=''){
                var encrypt = new JSEncrypt();
                encrypt.setPublicKey(publicKey);
                nowPwd = encrypt.encrypt(nowPwd);
            }
            if(newPwd !=null && $.trim(newPwd) !=''){
                var encrypt = new JSEncrypt();
                encrypt.setPublicKey(publicKey);
                newPwd = encrypt.encrypt(newPwd);
            }
            if(confirmPwd !=null && $.trim(confirmPwd) !=''){
                var encrypt = new JSEncrypt();
                encrypt.setPublicKey(publicKey);
                confirmPwd = encrypt.encrypt(confirmPwd);
            }
            $.ajax({
                url: baseloaction + "/web/uc/updateUserPwd",
                data:{
                    "nowPwd":nowPwd,
                    "newPwd":newPwd,
                    "confirmPwd":confirmPwd,
                    'sign':sign
                },
                dataType: "json",
                type: "post",
                success: function (result) {
                    icModale(0, "", result.message);
                    if (result.success == true) {
                        layer.close(index);
                    }else{
                        sign = result.keyMap.sign;
                        publicKey = result.keyMap.publicKey;
                    }
                }
            })
        });
    });

}